﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace CefDemo
{
    internal class MethodInvoker
    {
        public string InvokeMethod(string requestJson)
        {
            dynamic request = JsonConvert.DeserializeObject(requestJson);
            string dllPath = request.dllPath;
            string nameSpace = request.nameSpace;
            string className = request.className;
            string methodName = request.methodName;
            object[] parameters = request.parameters.ToObject<object[]>();

            // 安全验证：限制DLL加载目录
            string safeDir = Path.GetFullPath(Application.StartupPath);
            if (!Path.GetFullPath(dllPath).StartsWith(safeDir))
            {
                throw new Exception("禁止加载外部DLL");
            }

            try
            {
                // 加载DLL
                var assembly = System.Reflection.Assembly.LoadFrom(dllPath);
                
                // 获取类型
                var type = assembly.GetType(string.Concat(nameSpace, ".", className));
                object instance = Activator.CreateInstance(type);
                MethodInfo method = type.GetMethod(methodName);
                object result = method.Invoke(instance, parameters);

                return JsonConvert.SerializeObject(new { success = true, result });
            }
            catch (Exception ex)
            {
                return JsonConvert.SerializeObject(new { success = false, error = ex.Message });
            }
        }
    }
}